package com.zenika.zenbinding.client.widget;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class RadioGroup extends Composite implements ClickListener {

	private static int counter = 0;

	private Panel panel;
	private String name;
	private List listeners;
	private List widgetList;
	private String selectedItem;
	private boolean enabled = true;

	public RadioGroup() {
		this(getUniqueName());
	}

	public RadioGroup(boolean vertical) {
		this(getUniqueName(), vertical);
	}

	public RadioGroup(String name) {
		this(name, true);
	}

	public RadioGroup(String name, boolean vertical) {
		this.selectedItem = "none";
		this.name = name;
		this.listeners = new ArrayList();
		this.widgetList = new ArrayList();

		if (vertical)
			this.panel = new VerticalPanel();
		else
			this.panel = new HorizontalPanel();

		this.initWidget(this.panel);
	}

	// FIXME does lock actually work?
	private synchronized static String getUniqueName() {
		counter++;
		return "radio" + counter;
	}

	public void addItem(String item) {
		RadioButton radio = new RadioButton(this.name, item);
		radio.addClickListener(this);
		radio.setEnabled(enabled);
		this.widgetList.add(radio);
		this.panel.add(radio);
	}

	public void onClick(Widget sender) {
		RadioButton radio = (RadioButton) sender;
		this.setItemSelected(radio.getText());
		this.fireChange();
	}

	public void setItemSelected(String item) {
		Iterator iter = this.widgetList.iterator();
		while (iter.hasNext()) {
			RadioButton radio = (RadioButton) iter.next();
			String title = radio.getText();
			if (title.equals(item)) {
				radio.setChecked(true);
				this.selectedItem = item;
				break;
			}
		}
	}

	public String getSelectedItem() {
		return this.selectedItem;
	}

	public void addChangeListener(ChangeListener listener) {
		this.listeners.add(listener);
	}

	public void removeChangeListener(ChangeListener listener) {
		this.listeners.remove(listener);
	}

	private void fireChange() {
		System.out.println(this.selectedItem);
		Iterator iter = this.listeners.iterator();
		while (iter.hasNext()) {
			((ChangeListener) iter.next()).onChange(this);
		}
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
		for (int i = 0; i < this.widgetList.size(); i++) {
			RadioButton radio = (RadioButton) this.widgetList.get(i);
			radio.setEnabled(enabled);
		}
	}

}
